package com.galaxy.resource.controller;


import cn.hutool.core.util.RandomUtil;
import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.galaxy.common.core.constant.Constants;
import com.galaxy.common.core.constant.GlobalConstants;
import com.galaxy.common.core.domain.R;
import com.galaxy.common.ratelimiter.annotation.RateLimiter;
import com.galaxy.common.redis.utils.RedisUtils;
import com.galaxy.common.web.core.BaseController;
import org.apache.commons.lang.math.RandomUtils;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.api.entity.SmsResponse;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * 短信功能
 *
 * @author GalaxyMart
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/sms")
public class SysSmsController extends BaseController {

    /**
     * 短信验证码
     *
     * @param phonenumber 用户手机号
     */
    @RateLimiter(key = "#phonenumber", time = 60, count = 1)
    @GetMapping("/code")
    public R<Void> smsCaptcha(@NotBlank(message = "{user.phonenumber.not.blank}") String phonenumber) {
//        String key = GlobalConstants.CAPTCHA_CODE_KEY + phonenumber;
//        String code = RandomUtil.randomNumbers(4);
//        RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
//        // 验证码模板id 自行处理 (查数据库或写死均可)
//        String templateId = "SMS_154950909";
//        LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
//        map.put("code", code);
//        SmsBlend smsBlend = SmsFactory.getSmsBlend("config1");
//        SmsResponse smsResponse = smsBlend.sendMessage(phonenumber, templateId, map);
//        if (!smsResponse.isSuccess()) {
//            log.error("验证码短信发送异常 => {}", smsResponse);
//            return R.fail(smsResponse.getData().toString());
//        }

        //生产环境请求地址：app.cloopen.com
        String serverIp = "app.cloopen.com";
        //请求端口
        String serverPort = "8883";
        //主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN
        String accountSId = "2c94811c9787a27f0197c0fcb6161075";
        String accountToken = "84f9b349499942a4a07d241e6e83d703";
        //请使用管理控制台中已创建应用的APPID
        String appId = "2c94811c9787a27f0197c0fcb7be107c";
        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);
//        String to = "phonenumber";  // 仅可以测试官网中填入的测试号码
        String templateId = "1";
        String key1 = GlobalConstants.CAPTCHA_CODE_KEY + phonenumber;
        String code1 = RandomUtil.randomNumbers(4);
        RedisUtils.setCacheObject(key1, code1, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
        String[] datas = {code1, "1"};

        HashMap<String, Object> result = sdk.sendTemplateSMS(phonenumber,templateId,datas);
        if("000000".equals(result.get("statusCode"))){
            return R.ok();
        }else{
            //异常返回输出错误码和错误信息
            return R.fail("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
        }
    }

    @GetMapping("/verify")
    public R<Boolean> smsVerify(@NotBlank(message = "手机号不能为空") String phonenumber,
                            @NotBlank(message = "验证码不能为空") String code) {
        String key = GlobalConstants.CAPTCHA_CODE_KEY + phonenumber;
        String cacheCode = RedisUtils.getCacheObject(key);
        if (cacheCode == null) {
            return R.fail("验证码已失效",false);
        }
        if (!code.equals(cacheCode)) {
            return R.fail("验证码错误",false);
        }
        RedisUtils.deleteObject(key);
        return R.ok(true);
    }
}
